import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    goodList: [
      {
        name: '诸葛亮',
        price: 1000,
        num: 1,
        checked: false
      },
      {
        name: '蔡文姬',
        price: 1500,
        num: 1,
        checked: false
      },
      {
        name: '妲己',
        price: 2000,
        num: 1,
        checked: false
      },
      {
        name: '鲁班',
        price: 2200,
        num: 1,
        checked: false
      }
    ]
  },
  getters: {
    isAll (state) {
      return state.goodList.every(item => item.checked)
    },
    totalPrice (state) {
      // return state.goodList.reduce((sum, item) => sum + (item.price * item.num), 0)
      return state.goodList.reduce((sum, item) => item.checked ? sum + (item.price * item.num) : sum + 0, 0)
    }
  },
  mutations: {
    goodChecked (state, obj) {
      state.goodList[obj.index].checked = obj.val
    },
    allChecked (state, val) {
      state.goodList.forEach(item => { item.checked = val })
    },
    delGood (state, name) {
      state.goodList = state.goodList.filter(item => item.name !== name)
    },
    numUpdate (state, obj) {
      if (obj.number) {
        state.goodList[obj.index].num = obj.number
      }
    }
  },
  actions: {
  },
  modules: {
  }
})
